package org.chen.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.chen.dto.TaskDetailDTO;
import org.chen.model.CommentTask;
import org.chen.progress.BatchProgressDTO;
import org.chen.request.BatchCommentRequestDTO;
import org.chen.request.BatchUpdateRequest;
import org.chen.request.CommentRequestDTO;
import org.chen.service.impl.CommentBatchServiceImpl;
import org.chen.service.impl.CommentTaskExecutionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/send")
@Slf4j
public class SendCommentController {
    @Autowired
    private CommentBatchServiceImpl batchCommentService;

    @Autowired
    private CommentTaskExecutionService commentTaskExecutionService;


    @PostMapping("/post")
    public ResponseEntity<String> postComment(@RequestBody CommentRequestDTO request) {

        CommentTask task = CommentTask.builder()
                .websiteUrl(request.getWebsiteUrl())
                .nickname(request.getNickname())
                .commentContent(request.getCommentContent())
                .email(request.getEmail())
                .build();

        commentTaskExecutionService.attemptComment(task);

        return ResponseEntity.ok("评论发送成功");
    }

    /**
     * 批量发送评论
     */
    @PostMapping("/batch")
    public ResponseEntity<Map<String, Object>> createBatchComment(
            @RequestBody @Valid BatchCommentRequestDTO request) {
        try {
            // 立即返回批次号
            String batchNo = batchCommentService.createBatchCommentAsync(request);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("batchNo", batchNo);
            response.put("message", "批量评论任务已创建，请通过批次号查询进度");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("Failed to create batch comment", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    /**
     * 查询批次处理进度
     */
    @GetMapping("/batch/{batchNo}/progress")
    public ResponseEntity<Map<String, Object>> getBatchProgress(@PathVariable String batchNo) {
        try {
            BatchProgressDTO progress = batchCommentService.getBatchProgress(batchNo);
            return ResponseEntity.ok(Collections.singletonMap("data", progress));
        } catch (Exception e) {
            log.error("Failed to get batch progress", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    @GetMapping("/batch/{batchNo}/details")
    public ResponseEntity<IPage<TaskDetailDTO>> getBatchDetails(
            @PathVariable String batchNo,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        IPage<TaskDetailDTO> details = batchCommentService.getBatchDetails(batchNo, current, pageSize);
        return ResponseEntity.ok(details);
    }

    @PutMapping("/batch/update")
    public ResponseEntity<Void> updateBatchInfo(@RequestBody BatchUpdateRequest request) {
        batchCommentService.updateBatchInfo(request.getBatchNos(), request);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/batch/{batchNo}/resume")
    public ResponseEntity<Void> resumeBatch(@PathVariable String batchNo) {
        batchCommentService.resumeBatch(batchNo);
        return ResponseEntity.ok().build();
    }
}
